{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "data=pd.read_csv('analyst_ratings.csv')\n",
    "data2=data['stock']\n",
    "data3=data['headline']\n",
    "#去除列名，只保留数据，写入csv文件\n",
    "# data2.to_csv('stock.csv',index=False,header=False)\n",
    "data3.to_csv('headline.csv',index=False,header=False)\n",
    "data3.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "#将降序排列的股票代码和频数进行排名并保存\n",
    "#读取txt文件\n",
    "# 打开TXT文件和CSV文件\n",
    "#先在csv文件中添加列名\n",
    "with open('stock频数排列.txt', 'r') as txt_file, open('output.csv', 'w') as csv_file:\n",
    "    csv_file.write('stock,count\\n')\n",
    "    # 遍历TXT文件的每一行\n",
    "    for line in txt_file:\n",
    "        # 移除行尾的换行符，用逗号替换制表符\n",
    "        csv_line = line.strip().replace('\\t', ',') + '\\n'\n",
    "        # 写入CSV文件\n",
    "        csv_file.write(csv_line)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data=pd.read_csv('output.csv')\n",
    "#添加排名列，从1开始\n",
    "data['rank']=range(1,len(data)+1)\n",
    "# data.head()\n",
    "#输出格式为\"<排名>：<股票代码>，<次数>\"\n",
    "data['output']=data['rank'].astype(str)+':'+data['stock']+','+data['count'].astype(str)\n",
    "output=pd.DataFrame(data,columns=['output'])\n",
    "output.to_csv('stock_rank.csv',index=False,header=False)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "with open('headline_output.txt', 'r') as txt_file, open('headline_rank.csv', 'w') as csv_file:\n",
    "    csv_file.write('stock,count\\n')\n",
    "    # 遍历TXT文件的每一行\n",
    "    for line in txt_file:\n",
    "        # 移除行尾的换行符，用逗号替换制表符\n",
    "        csv_line = line.strip().replace('\\t', ',') + '\\n'\n",
    "        # 写入CSV文件\n",
    "        csv_file.write(csv_line)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
